package com.sharemarking.wa.platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author dxy
 */
@Service
public class GeocodingService {
    private static final String FIND_MAP_URL = "http://api.map.baidu.com/geocoding/v3/?output=json&ak=O9FZB1YZi7NTwsqtzSteT9fPdCYXsyzG&address=";

    private static final String DISTANCE_URL = "http://api.map.baidu.com/directionlite/v1/driving?ak=O9FZB1YZi7NTwsqtzSteT9fPdCYXsyzG&";

    private RestTemplate restTemplate;

    public GeocodingService() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 根据地址获取经纬度
     *
     * @param address
     * @return
     */
    private Map<String, Double> getLatAndLngByAddress(String address) {
        Map<String, Double> poiMap = null;
        String result;

        result = restTemplate.getForObject(FIND_MAP_URL + address, String.class);
        System.out.println(result);

        if (StringUtils.isNotBlank(result) && "0".equals(JSON.parseObject(result).get("status") + "")) {
            String lat = result.substring(result.indexOf("\"lat\":")
                    + ("\"lat\":").length(), result.indexOf("},\"precise\""));
            String lng = result.substring(result.indexOf("\"lng\":")
                    + ("\"lng\":").length(), result.indexOf(",\"lat\""));
            poiMap = ImmutableMap.of("lat", Double.parseDouble(lat), "lng", Double.parseDouble(lng));
        }
        return poiMap;
    }

    /**
     * 计算两个地址的距离（米）
     *
     * @param address
     * @param otherAddress
     * @return
     */
    public Integer getDistanceFromTwoPlaces(String address, String otherAddress) {
        Integer distance = null;
        if (StringUtils.isNotBlank(address) && StringUtils.isNotBlank(otherAddress)) {
            address = address.trim();
            otherAddress = otherAddress.trim();
            if (address.equals(otherAddress)) {
                return 0;
            }
            Map pointA = getLatAndLngByAddress(address);
            Map pointB = getLatAndLngByAddress(otherAddress);
            distance = getDistanceFromTwoPoints(pointA, pointB);
        }
        return distance;
    }

    /**
     * 获取两个经纬度之间的距离（单位：米）
     *
     * @param pointA
     * @param pointB
     * @return
     */
    private Integer getDistanceFromTwoPoints(Map pointA, Map pointB) {
        //lat 纬度值 lng 经度值
        Integer distance = 0;
        if (pointA != null && !pointA.isEmpty() && pointB != null && !pointB.isEmpty()) {
            double lat_a = (double) pointA.get("lat");
            double lng_a = (double) pointA.get("lng");
            double lat_b = (double) pointB.get("lat");
            double lng_b = (double) pointB.get("lng");

            if (lat_a == lat_b && lng_a == lng_b) {
                return 0;
            }

            String params = "origin=" + lat_a + "," + lng_a + "&destination=" + lat_b + "," + lng_b+"&tactics=3";
            String result = restTemplate.getForObject(DISTANCE_URL + params, String.class);

            JSONArray jsonArray = JSONObject.parseObject(result).getJSONObject("result").getJSONArray("routes");

            for (Object jsonObject : jsonArray) {
                System.out.println(JSONObject.parseObject(String.valueOf(jsonObject)).get("distance"));
                Integer temp = Integer.valueOf(String.valueOf(JSONObject.parseObject(String.valueOf(jsonObject)).get("distance")));
                if (distance < temp) {
                    distance = temp;
                }
            }
        }
        return Math.toIntExact(Math.round(distance * 0.001));
    }

    public static void main(String[] args) {
        GeocodingService geocodingService = new GeocodingService();
        System.out.println(geocodingService.getDistanceFromTwoPlaces("广东省佛山市顺德区鸡洲农贸市场", "广东省广州市黄埔区国际企业孵化器"));
    }
}

